/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.services.loan;

/**
 *
 * @author jay
 */

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.model.SelectItem;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import src.HibernateUtil;
import src.domain.loan.Loan;
import src.domain.loan.Loandd;
import src.services.CRUEDService;
import src.util.Constanta;

public class LoanddModel implements java.io.Serializable {
    
    private CRUEDService service;
    
    public LoanddModel() {
        service = new CRUEDService();
    }
    
    public Loandd getByNumber(String value) {
        Map<String, String> where = new HashMap<>();
        where.put("loandd.ddNo", value);
        return (Loandd) service.getObjectSQL("from Loandd dd", where);
    }
    
    public List<Loandd> findAll(Map<String, String> filters) {
        return (List<Loandd>) service.findAll("Loandd", filters);
    }
    
    public List<SelectItem> listAll() {
        return service.listAll("Loandd", "loanddId","ddNo");
    }

    public boolean saveData(boolean authorized, Loandd data) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        org.hibernate.Transaction tx = session.beginTransaction();
        boolean success;
        
        try {
            session.saveOrUpdate(data);
            
            if (authorized==true) {
                Loan loan = data.getLoan();
                loan.setLoanStatus(Constanta.LOANSTATUS_RUNNING);
                loan.setOwningAmount(loan.getPrincipalAmount());
                loan.setApprovalDate(data.getDdDate());
                session.saveOrUpdate(loan);
            }
            
            //update saving balance
          //  Query q = session.createSQLQuery(" { call SAVE_LOAN_BALANCE(?,?,?) }");
          //  q.setInteger(0,data.getLoan().getLoanId());  // first parameter, index starts with 0
          //  q.setBigDecimal(1, data.getLoan().getOwningAmount()); 
         //   q.setString(2, "D"); 
         //   q.executeUpdate();
                     
            tx.commit();
            success = true;  
            
        } catch (RuntimeException e) {
            
            if (tx != null && tx.isActive()) {
                try {
                    tx.rollback();
                } catch (HibernateException e1) {}
            }
            success = false;  
        }
                
        return success;
    }
    
    public boolean deleteData(Loandd data) {
        return service.deleteData(data);
    }
}
